package com.transsion.clouddemo.core

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Environment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.transsion.cloud_upload_sdk.httpservice.info.UploadFileSourceInfo
import com.transsion.cloud_upload_sdk.utils.Utils
import com.transsion.clouddemo.CloudApplication.Companion.context
import com.transsion.clouddemo.R
import com.transsion.clouddemo.core.config.ConfigFragment
import com.transsion.clouddemo.core.know.GuideFragment
import com.transsion.clouddemo.core.know.SyncFragment
import com.transsion.clouddemo.core.ulo.down.DownFragment
import com.transsion.clouddemo.core.ulo.other.OtherFragment
import com.transsion.clouddemo.core.ulo.upload.UploadFragment
import com.transsion.clouddemo.core.ulo.down.DownMessageItem
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import kotlin.random.Random

class DataGenerator {

    companion object {

        val customCss = """
            <style>
                /* 代码块样式 */
                pre, code {
                    font-size: 12px; /* 设置字体大小 */
                    word-wrap: break-word; /* 防止长单词超出视图 */
                    white-space: pre-wrap; /* 保持代码的格式 */
                    overflow-x: auto; /* 横向滚动条 */
                    background-color: #f5f5f5; /* 代码块背景色 */
                    padding: 8px; /* 内边距 */
                    border-radius: 4px; /* 圆角边框 */
                }
            </style>
        """.trimIndent()


        private val mTabRes = arrayOf(
            R.drawable.cloud_nav_know_normal,
            R.drawable.cloud_sync_normal,
            R.drawable.cloud_nav_setting_normal

        )

        private val mTabResPress = arrayOf(
            R.drawable.cloud_nav_know_sel,
            R.drawable.cloud_sync_sel,
            R.drawable.cloud_nav_setting_sel
        )

        val mTabTitle=arrayOf(
            R.string.cloud_know,
            R.string.cloud_try,
            R.string.cloud_config
        )

        private val mKnowFragments:Array<Fragment> = arrayOf(
            SyncFragment.newInstance(),GuideFragment.newInstance()
        )

        private val mTryFragments:Array<Fragment> = arrayOf(
            DownFragment.newInstance(), UploadFragment.newInstance(), OtherFragment.newInstance()
        )

        private var mConfigFragments:Array<Fragment> = arrayOf(
            ConfigFragment.newInstance()
        )

        val mFragments = arrayOf(mKnowFragments, mTryFragments, mConfigFragments)

        fun getFragments(position: Int) : Array<out Fragment> {
            return mFragments[position]
        }

        //云服务接口文档地址
        const val CLOUD_SDK_DOC="https://transsioner.feishu.cn/wiki/MZ0owWcOciXL6jkwqjgciTsJnFh"

        //业务场景列表
        val scenesName = mutableListOf("默认（云服务）", "笔记")
        val appIds = mutableListOf("infinix-cloud","notebook")
        val scenes = mutableListOf("9","4")




        //下载资源
        val downUrlRes: List<String> = listOf(
            "https://cdn-transcloud.palm.tech/156225482464007219/2024-12/2e54b704-2c8c-4408-8c90-59296ec5c41d-lock-wallpaper.png",
            "https://cdn-transcloud.palm.tech/156225482464007219/2024-12/413d7f06-c8d4-412e-bf7d-adb63684eac7-main-wallpaper.png")

        val downToUploadTest by lazy {
            val bitmap1 = BitmapFactory.decodeResource(context.resources, R.drawable.cloud_sync_sel)
            val bitmap2 = BitmapFactory.decodeResource(context.resources, R.drawable.cloud_nav_setting_sel)

            val baos1 = ByteArrayOutputStream()
            val baos2 = ByteArrayOutputStream()

            bitmap1.compress(Bitmap.CompressFormat.PNG, 100, baos1)
            bitmap2.compress(Bitmap.CompressFormat.PNG, 100, baos2)

            val data1= UploadFileSourceInfo("cloud_sync_sel.png",baos1.toByteArray().size,baos1.toByteArray())
            val data2= UploadFileSourceInfo("cloud_nav_setting_sel.png",baos2.toByteArray().size,baos2.toByteArray())

            arrayListOf(data1, data2)
        }


//        val multiPathData = getAllFilePathsInSDKDirectory()


//        val  multiObjectData = listAllFilesInDirectory(Utils.sdkDirectory())

        //初始化的down数据
        val urlDown=mutableListOf(DownMessageItem("下载成功!","下载失败!"),DownMessageItem("下载文件：","失败原因："))
        val sceneDown=mutableListOf(DownMessageItem("下载成功!","下载失败!"),DownMessageItem("下载文件：","失败原因："))
        val pointDown=mutableListOf(DownMessageItem("下载成功!","下载失败!"),DownMessageItem("下载文件：","失败原因："))

        //初始化的upload数据
        val easyUpload=mutableListOf(DownMessageItem("上传成功!","上传失败!"),DownMessageItem("上传文件：","失败原因："))
        val multiPathUpload=mutableListOf(DownMessageItem("上传成功!","上传失败!"),DownMessageItem("上传文件：","失败原因："))
        val multiObjectUpload=mutableListOf(DownMessageItem("上传成功!","上传失败!"),DownMessageItem("上传文件：","失败原因："))
        val breakPointUpload=mutableListOf(DownMessageItem("上传成功!","上传失败!"),DownMessageItem("上传文件：","失败原因："))


        //初始化删除文件信息的数据
        val removeData=mutableListOf(DownMessageItem("删除成功!","删除失败!"),DownMessageItem("删除本地文件路径：","失败原因："))




        //code与原因的映射关系
        val codeToReason = mapOf(
            0 to "",
            1 to "下载暂停",
            2 to "取消",
            -1 to "请求报错",
            3 to "没有token，需要先登录",
            4 to "没有请求数据，检查请求的数据",
            5 to "无需上传，云端已存在",
            20 to "内存不足",
            21 to "云空间已满",
            403 to "登录异常",
            400 to "参数异常",
            10007 to "客户端数据版本不正确"

        )

        @SuppressLint("InflateParams", "ResourceAsColor")
        fun setTabView(view: View, position: Int, selected: Boolean) {
            val tabText = view.findViewById<TextView>(R.id.tab_content_text)
            tabText.setTextColor(context.getColor(if (selected) R.color.cloud_text_selected else R.color.cloud_text_default))

            val tabImg = view.findViewById<ImageView>(R.id.tab_content_image)
            tabImg.setImageResource(if (selected) mTabResPress[position] else mTabRes[position])
        }

        @SuppressLint("ResourceAsColor", "InflateParams")
        fun getTabView(context: Context, position: Int): View {
            val view=LayoutInflater.from(context).inflate(R.layout.home_tab_content, null)
            val tabText = view.findViewById<TextView>(R.id.tab_content_text)

            tabText.text = context.getString(mTabTitle[position])
            tabText.setTextColor(context.getColor(if (position==0) R.color.cloud_text_selected else R.color.cloud_text_default))

            val tabImg = view.findViewById<ImageView>(R.id.tab_content_image)
            tabImg.setImageResource(if (position==0) mTabResPress[position] else mTabRes[position])
            return view
        }





//        fun refreshConfigFragment() {
//            mConfigFragments = arrayOf(ConfigFragment.newInstance())
//        }

        fun finishConfigFragment() {
            mConfigFragments[0]
        }


        /**
         * 将实例图片转到外部存储并得到文件path的list
         */
        fun getAllFilePathsInDirectory(): List<String> {
            val targetDir = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "CloudAppImages")
            val filePaths = mutableListOf<String>() // 用于存储文件路径的列表

            if (targetDir.exists() && targetDir.isDirectory) {
                targetDir.listFiles()?.forEach { file ->
                    filePaths.add(file.absolutePath) // 添加每个文件的绝对路径到列表中
                }
            }
            return filePaths
        }


        /**
         * 将实例图片转到云服务SDK默认存储位置Utils.sdkDirectory()并得到文件path的list
         */
        fun getAllFilePathsInSDKDirectory(): List<String> {
            val targetDir = File(Utils.sdkDirectory())
            val filePaths = mutableListOf<String>() // 用于存储文件路径的列表
            if (targetDir.listFiles()!!.size <= 1) {
                copyDrawablesToDirectory(context)
            }
            if (targetDir.exists() && targetDir.isDirectory) {
                targetDir.listFiles()?.forEach { file ->
                    if (file.isFile) {
                        val generateUniqueFileName = generateUniqueFileName(file)
                        file.renameTo(File(generateUniqueFileName))
                        filePaths.add(File(generateUniqueFileName).absolutePath) // 添加每个文件的绝对路径到列表中
                    }
                }
            }
            return filePaths
        }

        /**
         * 根据时间戳和随机数来生成不重复的文件名保证上传成功
         */
        @SuppressLint("SimpleDateFormat")
        fun generateUniqueFileName(file: File): String {
            val timeStamp = SimpleDateFormat("yyyyMMddHHmmss").format(Date()) // 获取当前时间戳
            val randomInt = Random.nextInt(1000, 9999) // 生成随机数
            val extension = if (file.extension.isNotEmpty()) ".${file.extension}" else "" // 保留原扩展名（如果有）
            return "${file.parent}${File.separator}${timeStamp}_$randomInt$extension"
            // 使用时间戳和随机数生成唯一文件名
        }

        /**\
         * 获取文件夹中所有文件列表
         */
        fun listAllFilesInDirectory(directoryPath: String): List<File> {

            if (File(Utils.sdkDirectory()).listFiles()!!.size <= 1) {
                copyDrawablesToDirectory(context)
            }
            val resultList = mutableListOf<File>() // 创建一个空的可变列表用于存储文件
            val directory = File(directoryPath) // 创建表示目录的File对象
            if (directory.exists() && directory.isDirectory) { // 检查路径是否存在且是否为目录
                directory.listFiles()?.forEach { file -> // 遍历目录中的所有文件和子目录
                    if (file.isFile) { // 如果是文件
                        val generateUniqueFileName = generateUniqueFileName(file)
                        file.renameTo(File(generateUniqueFileName))
                        resultList.add(File(generateUniqueFileName)) // 将文件添加到结果列表
                    }
                }
            }
            return resultList // 返回文件列表
        }


        /**
         * 将资源图片放置到目标路径下
         */
        fun copyDrawablesToDirectory(context: Context){
            // 获取所有的drawable资源ID
            val drawableIds = listOf(
                R.drawable.cloud_clear_sel,
                R.drawable.cloud_clear_normal,
                R.drawable.cloud_copy_sel,
                R.drawable.cloud_copy_normal,
                R.drawable.cloud_nav_know_sel,
                R.drawable.cloud_nav_know_normal,
                R.drawable.cloud_nav_setting_sel,
                R.drawable.cloud_nav_setting_normal,
                R.drawable.cloud_sync_sel,
                R.drawable.cloud_sync_normal,
                R.drawable.cloud_know_qa_100
            ) // 这里列出所有的drawable ID

            // 目标路径
//        val targetDir = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "CloudAppImages")
            val targetDir = File(Utils.sdkDirectory())


            if (!targetDir.exists()) {
                targetDir.mkdirs() // 确保目标目录存在
            }
            drawableIds.forEach { drawableId ->
                val bitmap = BitmapFactory.decodeResource(context.resources, drawableId) // 从资源中解码图片
                val fileName = context.resources.getResourceEntryName(drawableId) + ".png" // 获取资源的名称作为文件名
                val file = File(targetDir, fileName) // 创建文件对象

                try {
                    // 使用 ByteArrayOutputStream 先将 Bitmap 写入字节数组
                    val byteArrayOutputStream = ByteArrayOutputStream()
                    if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)) {
                        // 将字节数组写入文件
                        FileOutputStream(file).use { outputStream ->
                            outputStream.write(byteArrayOutputStream.toByteArray())
                        }
                    } else {
                        throw IOException("Failed to compress bitmap")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    Log.e("Error", "Failed to save image: ${e.message}")
                }
            }
        }


        /**
         * 清理所有的资源文件
         */
        fun clearImagesFromExternalStorage() {
//        val targetDir = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "CloudAppImages")
            val targetDir = File(Utils.sdkDirectory())

            if (targetDir.exists()) {
                targetDir.listFiles()?.forEach { file ->
                    if (file.isFile && (file.extension == "png" || file.extension == "jpg" || file.extension == "jpeg")) {
                        file.delete() // 删除图片文件
                    }
                }
            }
        }


















    }









}
